package com.gitee.zw.irmp.common.utils;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.util.WebUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

@Slf4j
public class HttpUtils {

    public static String getRequestRootEncoded(HttpServletRequest request) throws UnsupportedEncodingException {
        String url = request.getParameter("_url");
        if (url == null) {
            StringBuffer burl = request.getRequestURL();
            String cp = request.getContextPath();
            burl.substring(burl.indexOf(cp) + cp.length(), burl.length());
            url = burl.toString();
        } else if (url.endsWith("/")) {
            url = url.substring(0, url.length() - 1);
        }
        return URLEncoder.encode(url, "utf-8");
    }

    public static String getCookieValue(HttpServletRequest request, String key) {
        Cookie cookie = WebUtils.getCookie(request, key);
        if (cookie != null) {
            String value = cookie.getValue();
            try {
                value = URLDecoder.decode(value, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("Error to decode:" + value, e);
            }
            log.trace("cookie {} found as: {}", key, value);
            return value;
        }
        log.trace("cookie {} not found", key);
        return null;
    }

    public static void setCookieValue(HttpServletRequest request, HttpServletResponse response, String key, String value) {
        try {
            value = URLEncoder.encode(value, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Error to encode:" + value, e);
        }
        Cookie cookie = new Cookie(key, value);
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);
        log.trace("cookie set: {}", cookie);
    }
}
